package com.venus.common.service.impl;

import java.io.Serializable;
import java.util.List;

import javax.servlet.ServletContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import com.venus.common.dao.IBaseDAO;
import com.venus.common.service.IBaseService;

public class BaseServiceImpl implements IBaseService {

	protected final Log log = LogFactory.getLog(getClass());
	
	protected IBaseDAO baseDAO;
	
	private static WebApplicationContext context = null;
    private static ServletContext servletContext = null;
    private static ContextLoader contextLoader = new ContextLoader();
	
	public void setBaseDAO(IBaseDAO baseDAO) {
		this.baseDAO = baseDAO;
	}

	public boolean deleteModel(Object obj) {
		baseDAO.deleteModel(obj);
		return false;
	}

	public <T> T getModel(Class<T> clazz, Serializable id) {
		
		return this.baseDAO.getModel(clazz, id);
	}

	public boolean saveModel(Object obj) {
		this.baseDAO.saveModel(obj);
		return false;
	}

	public boolean updateModel(Object obj) {
		this.baseDAO.updateModel(obj);
		return false;
	}

	public List exeHql(String hql) {
		return this.baseDAO.exeHql(hql);
	}
	
	/**
	 * 从spring容器中得到一个实例
	 * @param strObjectName 实例名
	 * @return
	 */
	public Object getBean(String strObjectName){
		if(context == null)
        {
            if(contextLoader == null)
            {
                contextLoader = new ContextLoader();
            }
            if(servletContext == null)
            {
                throw new RuntimeException("servletContext must be set first!");
            }
            context = ContextLoader.getCurrentWebApplicationContext();
            if(context == null)
            {
                context = contextLoader.initWebApplicationContext(servletContext);
            }
        }
		return context.getBean(strObjectName);
	}
	
}
